package com.qiangqiang.aop;

import com.qiangqiang.entity.Dormitory;
import com.qiangqiang.entity.Student;
import com.qiangqiang.enums.DormitoryEnum;
import com.qiangqiang.enums.StudentEnum;
import com.qiangqiang.exception.DormitoryException;
import com.qiangqiang.exception.StudentException;
import com.qiangqiang.repository.DormitoryRepository;
import com.qiangqiang.repository.StudentRepository;
import com.qiangqiang.service.StudentService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by q on 2018/3/8.
 */
@Aspect
@Component
public class CheckByAop {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private DormitoryRepository dormitoryRepository;


    @Pointcut("@annotation(com.qiangqiang.aop.annotation.CheckHasStudent)")
    public void isExistStudent(){}

    @Pointcut("@annotation(com.qiangqiang.aop.annotation.CheckHasDormitory)")
    public void isExistDormitory(){}


    @Around("isExistStudent()")
    public java.lang.Object checkStudent(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取参数列表
        Object[] arguments=joinPoint.getArgs();
        //获得id
        String id= (String) arguments[0];
        Student student=studentRepository.queryBySId(id);
        //不存在该学生时
        if(student==null){
            throw new StudentException(StudentEnum.SID_NOT_EXIST);
        }
        Object result=joinPoint.proceed(joinPoint.getArgs());
        return result;
    }


    @Around("isExistDormitory()")
    public Object checkDoemitory(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取参数列表
        Object[] arguments=joinPoint.getArgs();
        //获得id
        String id= (String) arguments[0];
        Dormitory dormitory=dormitoryRepository.findOne(id);
        if(dormitory==null){
            throw new DormitoryException(DormitoryEnum.DORMITORY_NOT_EXIST);
        }
        Object result=joinPoint.proceed(joinPoint.getArgs());
        return result;
    }

}
